package com.ml.ws.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component("userLoginService")
public class UserLoginServiceImpl implements UserDetailsService {

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		
		System.out.println("用户名-------------"+username);  
		
		UserLogin userLogin =  null;  
        if(username != null && !"".equals(username)&& username.indexOf("@") > 0){  
              userLogin = UserLoginDao.findByEmail(username);  
              username = userLogin.getNick();  
        }else{  
            userLogin = UserLoginDao.findByNick(username);  
        }  
        
        if(userLogin == null){
        	throw new UsernameNotFoundException("用户不存在");
        }
        
        System.out.println("user type ---"+userLogin.getUserType());  
//        String nick = userLogin.getNick();  
//        String email = userLogin.getEmail();  
//        String mobile = userLogin.getMobile();  
        int userType = userLogin.getUserType();  
        List<GrantedAuthority> resultAuths = new ArrayList<GrantedAuthority>();  
        
  
        // 前台用户  
        if (userType == 1) {  
            resultAuths.add(new SimpleGrantedAuthority("ROLE_USER"));  
        } else {  
            resultAuths.add(new SimpleGrantedAuthority("ROLE_BACK_USER"));  
        }  
          
//        return new WrappedUserLogin(userLogin.getId(), email, nick, mobile, userLogin.getPassword(), userType, resultAuths);
        return new WrappedUserLogin(userLogin, resultAuths);
	} 

}
